﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;

namespace XJay.Identity.Extend
{
    /// <summary>
    /// 自定义授权处理
    /// </summary>
    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        public PermissionHandler()
        {

        }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (context.Resource is HttpContext httpContext)
            {
                
                var isPermission = httpContext.User.Claims.Where(p => p.Type == "Role" && p.Value == requirement.RoleID).FirstOrDefault() != null;

                if (isPermission)
                {
                    context.Succeed(requirement); // 显式的声明验证成功
                }
            }
            else context.Fail();
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 用户认证信息必要参数类
    /// </summary>
    public class PermissionRequirement : IAuthorizationRequirement
    {
        /// <summary>
        /// 角色id
        /// </summary>
        public string RoleID { get; set; }
        public PermissionRequirement(string roleId)
        {
            RoleID = roleId;
        }
    }
}
